/**
 * AspectSense project
 *
 * Middleware for annotation-based, context-aware and adaptive services for
 * mobile and ubiquitous computing
 *
 * This project is an open-source effort, started at the University of Cyprus
 * [http://www.ucy.ac.cy].
 *
 * More information about the project is available at
 * [http://code.google.com/p/aspectsense]
 *
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option)
 * any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

package org.aspectsense.example_apps.multipleUI;

import com.sun.speech.freetts.audio.AudioPlayer;
import com.sun.speech.freetts.audio.JavaStreamingAudioPlayer;
import org.aspectsense.annotations.Component;
import org.aspectsense.annotations.RequiredService;
import org.aspectsense.annotations.Service;
import org.aspectsense.annotations.ServiceUtility;
import org.aspectsense.framework.DefaultComponent;
import org.aspectsense.framework.Stateful;

import javax.sound.sampled.AudioFormat;
import java.io.Serializable;
import java.rmi.RemoteException;
import java.util.StringTokenizer;
import java.util.logging.Logger;

/**
 * <p/>
 * Date: Jul 13, 2007<br/>
 * Time: 2:39:42 PM
 * </p>
 *
 * @author Nearchos Paspallis [nearchos@cs.ucy.ac.cy]
 */
@Component(
        displayID = "AudioUI"
)
@Service(
        serviceType = UIService.class
)
@ServiceUtility(
        targetServiceType = UIService.class,
        utilityFunction =
                "context[context.user.handsfree-required] ? 0.5 : 0 + "
              + "0.5 * utility[org.aspectsense.example_apps.multipleUI.AudioProcessorService]"
)
public class AudioUI extends DefaultComponent implements UIService, Stateful
{
    private Serializable state = "";

    private AudioPlayer audioPlayer;

    @RequiredService(
            variationPointID = "sample_app1.audioProcessor"
    )
    private AudioProcessorService audioProcessor;

    // implement the DynamicallyReconfigurable interface
    public void init()
    {
        super.init();

System.out.print("initializing audio player ...");
        audioPlayer = new JavaStreamingAudioPlayer();
        audioPlayer.setAudioFormat(new AudioFormat(16000, 16, 1, true, true));
System.out.println(" done!");
    }

    public void activate()
    {
System.out.print("activating audio player ...");
        super.activate();
System.out.println(" done!");
    }

    public void suspend()
    {
System.out.print("suspending audio player ...");
        super.suspend();
System.out.println(" done!");
    }

    public void finit()
    {
        super.finit();

System.out.print("finalizing audio player ...");
        audioPlayer.drain();
        audioPlayer.close();
        audioPlayer = null; // dereference
System.out.println(" done!");
    }

    public static final int MAX_WORD_SIZE = 16;

    // implement the AudioOutput interface
    public void communicateText(String text)
    {
        Logger.getAnonymousLogger().finest("Communicating text: " + text);

        this.state = text;

        StringTokenizer stringTokenizer = new StringTokenizer(text);

        try
        {
            StringBuffer stringBuffer = new StringBuffer();
            String nextToken;

            while(stringTokenizer.hasMoreTokens())
            {
                nextToken = stringTokenizer.nextToken();

                if(stringBuffer.length() + nextToken.length() <= MAX_WORD_SIZE)
                {
                    stringBuffer.append(" ").append(nextToken);
                }
                else
                {
                    playWords(stringBuffer.toString());
                    stringBuffer = new StringBuffer();
                    stringBuffer.append(nextToken);
                }
            }

            playWords(stringBuffer.toString());
        }
        catch(RemoteException re)
        {
            throw new RuntimeException(re);
        }
    }

    private void playWords(final String words)
        throws RemoteException
    {
System.out.println("audioPlayer instance: " + audioPlayer + "in " + this.toString());//todo
        final byte [] buffer = audioProcessor.composeBytesForText(words);
        audioPlayer.begin(0);
        audioPlayer.write(buffer, 0, buffer.length);
        audioPlayer.end();
    }

    // -------------- Implementation of the Stateful interface -------------- //

    public Object getState()
    {
        return state;
    }

    public Object setState(Object state)
    {
        Serializable oldState = this.state;
        this.state = (Serializable) state;
        return oldState;
    }

    // ---------- End of Implementation of the Stateful interface ----------- //
}